package com.xw.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xw.common.TokenHandler;
import com.xw.dao.SubjectMapper;
import com.xw.entity.Subject;
import com.xw.entity.User;
import com.xw.exp.ServiceException;
import com.xw.manger.AliyunManger;
import com.xw.req.PageRequest;
import com.xw.service.SubjectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 15536
 * @description 针对表【subject】的数据库操作Service实现
 * @createDate 2024-12-05 20:15:05
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Resource
    private SubjectMapper subjectMapper;


    @Resource
    private TokenHandler tokenHandler;

    @Resource
    private AliyunManger aliyunManger;


    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void insertSubject(Subject subject) {
        User userInfo = tokenHandler.getUserInfo();
        subject.setCreateUser(userInfo.getId());
        subject.setCreateTime(new Date());
        subjectMapper.insert(subject);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void deleteSubject(Long id) {
        Subject subject = subjectMapper.selectById(id);
        subjectMapper.deleteById(id);
        // 删除阿里云的 视频
        aliyunManger.deleteVideo(subject.getVideoId());

    }

    @Override
    public List<Subject> getAllSubjects() {
        return subjectMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateSubject(Subject subject) {
        subjectMapper.updateById(subject);
    }

    @Override
    public void deleteBatchByIds(List<Integer> ids) {
        if (CollUtil.isEmpty(ids)) {
            throw new ServiceException("400","请选择要删除的数据");
        }
        // 可以自行优化 使用java8 lambda表达式 统一查询出来 然后调用 aliyunManger.deleteBatch 删除
        ids.forEach(id -> {
            Subject subject = subjectMapper.selectById(id);
            // 删除阿里云的 视频
            aliyunManger.deleteVideo(subject.getVideoId());
        });
        removeBatchByIds(ids);
    }

    @Override
    public PageInfo<Subject> page(PageRequest<Subject> pageRequest) {
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<Subject> categories = list(
                new LambdaQueryWrapper<Subject>()
                        .like(Subject::getSubjectName, pageRequest.getQ().getSubjectName())
        );
        PageInfo<Subject> pageInfo = new PageInfo<>(categories);
        return pageInfo;
    }
}




